package com.sheng.project.study.genericity;

import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSON;
import lombok.*;

import java.io.Serializable;

/**
 * @author liusheng
 * @date 2023/07/06
 */
public class Demo7 {
    /**
     * 返回一个用户信息
     *
     * @return
     */
    public static Result<UserModel> getUser() {
        UserModel userModel = UserModel.builder().id(1).name("黄金鹏").build();
        Result<UserModel> result = Result.<UserModel>builder().code("1").subCode(null).msg("操作成功").data(userModel).build();
        return result;
    }

    /**
     * 用户json信息
     *
     * @return
     */
    public static String getUserString() {
        return JSON.toJSONString(getUser());
    }

    public static void main(String[] args) {
        String userString = getUserString();
        // 会输出：{"code":"1","data":{"id":1,"name":"黄金鹏"},"msg":"操作成功"}
        System.out.println(userString);
        // 下面我们需要将 userString 反序列化为 Result<UserModel> 对象
        Result<UserModel> userModelResult = JSON.parseObject(userString, new TypeReference<Result<UserModel>>() {
        }.getType());
        // 我们来看看 Result 中的 data 是不是 UserModel 类型的
        System.out.println(userModelResult.getData().getClass());
    }

    /**
     * 通用的返回值类型
     *
     * @param <T>
     */
    @Getter
    @Setter
    @ToString
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Result<T> implements Serializable {
        private String code;
        private String subCode;
        private String msg;
        private T data;
    }

    @Getter
    @Setter
    @Builder
    @ToString
    @NoArgsConstructor
    @AllArgsConstructor
    public static class UserModel {
        private Integer id;
        private String name;
    }
}
